package cn.harry.cabinet.view.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.harry.cabinet.R
import cn.harry.cabinet.constants.OperationLogConstants
import cn.harry.cabinet.model.entity.OperationLog
import cn.harry.cabinet.repository.OperationLogRepository
import cn.harry.cabinet.view.adapter.OperationLogAdapter
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

/**
 * 操作日志查询页面
 * 支持按操作类型、结果等条件查询
 */
class OperationLogFragment : BaseFragment() {

    private lateinit var repository: OperationLogRepository
    private lateinit var adapter: OperationLogAdapter

    // UI组件
    private lateinit var searchCard: View
    private lateinit var searchContentLayout: LinearLayout
    private lateinit var spinnerOperationType: Spinner
    private lateinit var spinnerResult: Spinner
    private lateinit var btnSearch: Button
    private lateinit var btnReset: Button
    private lateinit var btnClearLogs: Button
    private lateinit var tvToggleSearch: TextView
    private lateinit var tvTotalCount: TextView
    private lateinit var tvFilteredCount: TextView
    private lateinit var swipeRefreshLayout: androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    private lateinit var recyclerView: RecyclerView
    private lateinit var emptyView: View
    private lateinit var progressBar: ProgressBar

    // 查询条件
    private var selectedOperationType: String? = null
    private var selectedResult: String? = null

    // 分页
    private val pageSize = 50
    private var currentOffset = 0
    private var isLoading = false
    private var hasMoreData = true

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_operation_log, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        repository = OperationLogRepository(requireActivity().application)

        initViews(view)
        setupSpinners()
        setupRecyclerView()
        setupListeners()
        setupEmptyState()

        loadInitialData()
    }
    
    private fun setupEmptyState() {
        // 自定义空状态的图标和文字
        emptyView.findViewById<ImageView>(R.id.emptyStateIcon)?.apply {
            setImageResource(R.drawable.ic_settings)
        }
        emptyView.findViewById<TextView>(R.id.emptyStateTitle)?.text = "暂无日志记录"
        emptyView.findViewById<TextView>(R.id.emptyStateMessage)?.text = "请调整查询条件后重试"
    }
    
    /**
     * 重写主题应用方法，确保主题切换时正确更新UI
     */
    override fun applyThemeToFragment() {
        super.applyThemeToFragment()
        
        view?.let { fragmentView ->
            try {
                val currentTheme = getCurrentTheme()
                val themeColors = cn.harry.cabinet.theme.manager.ThemeManager.getThemeColors(currentTheme)
                
                // 更新背景颜色
                fragmentView.setBackgroundColor(
                    androidx.core.content.ContextCompat.getColor(requireContext(), themeColors.background)
                )
                
                // 更新文本颜色
                updateTextColors(themeColors)
                
            } catch (e: Exception) {
                android.util.Log.w("OperationLogFragment", "Failed to apply theme: ${e.message}")
            }
        }
    }
    
    /**
     * 更新文本颜色以匹配主题
     */
    private fun updateTextColors(themeColors: cn.harry.cabinet.theme.manager.ThemeManager.ThemeColors) {
        try {
            val primaryColor = androidx.core.content.ContextCompat.getColor(requireContext(), themeColors.onSurface)
            val secondaryColor = androidx.core.content.ContextCompat.getColor(requireContext(), themeColors.onSurfaceVariant)
            val accentColor = androidx.core.content.ContextCompat.getColor(requireContext(), themeColors.primary)
            
            // 更新统计文本颜色
            tvTotalCount.setTextColor(secondaryColor)
            tvFilteredCount.setTextColor(secondaryColor)
            
            // 更新展开/收起按钮颜色
            tvToggleSearch.setTextColor(accentColor)
            
        } catch (e: Exception) {
            android.util.Log.w("OperationLogFragment", "Failed to update text colors: ${e.message}")
        }
    }

    private fun initViews(view: View) {
        searchCard = view.findViewById(R.id.searchCard)
        searchContentLayout = view.findViewById(R.id.searchContentLayout)
        spinnerOperationType = view.findViewById(R.id.spinnerOperationType)
        spinnerResult = view.findViewById(R.id.spinnerResult)
        btnSearch = view.findViewById(R.id.btnSearch)
        btnReset = view.findViewById(R.id.btnReset)
        btnClearLogs = view.findViewById(R.id.btnClearLogs)
        tvToggleSearch = view.findViewById(R.id.tvToggleSearch)
        
        // 统计信息需要从 include 布局中获取
        val statsLayout = view.findViewById<View>(R.id.statsLayout)
        tvTotalCount = statsLayout.findViewById(R.id.tvTotalCount)
        tvFilteredCount = statsLayout.findViewById(R.id.tvFilteredCount)
        
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout)
        recyclerView = view.findViewById(R.id.recyclerViewLogs)
        emptyView = view.findViewById(R.id.emptyView)
        progressBar = view.findViewById(R.id.progressBar)
    }

    private fun setupSpinners() {
        // 操作类型下拉框
        val operationTypes = listOf(
            "全部" to null,
            "用户认证" to OperationLogConstants.OperationType.USER_AUTH,
            "取仪器" to OperationLogConstants.OperationType.INSTRUMENT_TAKE,
            "还仪器" to OperationLogConstants.OperationType.INSTRUMENT_RETURN,
            "数据同步" to OperationLogConstants.OperationType.DATA_SYNC,
            "接口调用" to OperationLogConstants.OperationType.API_CALL,
            "配置修改" to OperationLogConstants.OperationType.CONFIG_CHANGE,
            "定时任务" to OperationLogConstants.OperationType.SCHEDULED_TASK,
            "系统事件" to OperationLogConstants.OperationType.SYSTEM_EVENT
        )

        val typeAdapter = ArrayAdapter(
            requireContext(),
            R.layout.spinner_item_light,
            operationTypes.map { it.first }
        )
        typeAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item_light)
        spinnerOperationType.adapter = typeAdapter

        spinnerOperationType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                selectedOperationType = operationTypes[position].second
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                selectedOperationType = null
            }
        }

        // 操作结果下拉框
        val results = listOf(
            "全部" to null,
            "成功" to OperationLogConstants.Result.SUCCESS,
            "失败" to OperationLogConstants.Result.FAILED,
            "进行中" to OperationLogConstants.Result.PENDING
        )

        val resultAdapter = ArrayAdapter(
            requireContext(),
            R.layout.spinner_item_light,
            results.map { it.first }
        )
        resultAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item_light)
        spinnerResult.adapter = resultAdapter

        spinnerResult.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                selectedResult = results[position].second
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                selectedResult = null
            }
        }
    }

    private fun setupRecyclerView() {
        adapter = OperationLogAdapter { log ->
            showLogDetail(log)
        }

        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = adapter

        // 滚动监听，实现分页加载
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val lastVisiblePosition = layoutManager.findLastVisibleItemPosition()
                val totalItemCount = layoutManager.itemCount

                if (!isLoading && hasMoreData && lastVisiblePosition >= totalItemCount - 5) {
                    loadMoreData()
                }
            }
        })
    }

    private fun setupListeners() {
        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener {
            performSearch()
        }

        // 查询按钮
        btnSearch.setOnClickListener {
            performSearch()
        }

        // 重置按钮
        btnReset.setOnClickListener {
            resetFilters()
        }

        // 展开/收起查询条件
        tvToggleSearch.setOnClickListener {
            toggleSearchCard()
        }

        // 清空日志按钮
        btnClearLogs.setOnClickListener {
            showClearLogsConfirmation()
        }
    }

    private fun toggleSearchCard() {
        val isExpanded = searchCard.visibility == View.VISIBLE
        if (isExpanded) {
            // 收起：隐藏查询卡片
            searchCard.visibility = View.GONE
            tvToggleSearch.text = "展开 ▼"
        } else {
            // 展开：显示查询卡片
            searchCard.visibility = View.VISIBLE
            tvToggleSearch.text = "收起 ▲"
        }
    }

    private fun loadInitialData() {
        currentOffset = 0
        hasMoreData = true
        performSearch()
        loadTotalCount()
    }

    private fun performSearch() {
        currentOffset = 0
        hasMoreData = true
        isLoading = true
        progressBar.visibility = View.VISIBLE

        lifecycleScope.launch {
            try {
                val logs = repository.searchLogs(
                    type = selectedOperationType,
                    result = selectedResult,
                    operatorId = null,
                    startTime = null,
                    endTime = null,
                    limit = pageSize,
                    offset = currentOffset
                )

                adapter.setLogs(logs)
                currentOffset += logs.size
                hasMoreData = logs.size >= pageSize

                updateUI(logs)
            } catch (e: Exception) {
                showToast("查询失败: ${e.message}")
            } finally {
                isLoading = false
                progressBar.visibility = View.GONE
            }
        }
    }

    private fun loadMoreData() {
        if (isLoading || !hasMoreData) return

        isLoading = true
        adapter.setLoadingMore(true)

        lifecycleScope.launch {
            try {
                val logs = repository.searchLogs(
                    type = selectedOperationType,
                    result = selectedResult,
                    operatorId = null,
                    startTime = null,
                    endTime = null,
                    limit = pageSize,
                    offset = currentOffset
                )

                if (logs.isNotEmpty()) {
                    adapter.appendLogs(logs)
                    currentOffset += logs.size
                    hasMoreData = logs.size >= pageSize

                    tvFilteredCount.text = "筛选结果: ${adapter.getLogs().size}"
                } else {
                    hasMoreData = false
                }
            } catch (e: Exception) {
                showToast("加载失败: ${e.message}")
            } finally {
                isLoading = false
                adapter.setLoadingMore(false)
            }
        }
    }

    private fun loadTotalCount() {
        lifecycleScope.launch {
            try {
                val count = repository.getCount()
                tvTotalCount.text = "总数: $count"
            } catch (e: Exception) {
                // Ignore
            }
        }
    }

    private fun resetFilters() {
        spinnerOperationType.setSelection(0)
        spinnerResult.setSelection(0)

        performSearch()
    }

    private fun updateUI(logs: List<OperationLog>) {
        // 停止刷新动画
        swipeRefreshLayout.isRefreshing = false
        
        if (logs.isEmpty()) {
            recyclerView.visibility = View.GONE
            emptyView.visibility = View.VISIBLE
        } else {
            recyclerView.visibility = View.VISIBLE
            emptyView.visibility = View.GONE
        }

        tvFilteredCount.text = "筛选结果: ${logs.size}"
    }

    private fun showLogDetail(log: OperationLog) {
        // 显示日志详情对话框，展示所有字段
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
        
        val message = buildString {
            // 基本信息
            appendLine("━━━━━━ 基本信息 ━━━━━━")
            appendLine("日志ID: ${log.id}")
            appendLine("时间: ${dateFormat.format(Date(log.timestamp))}")
            appendLine("操作类型: ${log.operationType}")
            log.operationSubType?.let { appendLine("子类型: $it") }
            appendLine("结果: ${log.result}")
            appendLine()
            
            // 操作描述
            appendLine("━━━━━━ 操作描述 ━━━━━━")
            appendLine(log.description)
            appendLine()
            
            // 操作人信息
            if (log.operatorId != null || log.operatorName != null || log.operatorEmployeeId != null) {
                appendLine("━━━━━━ 操作人信息 ━━━━━━")
                log.operatorId?.let { appendLine("操作人ID: $it") }
                log.operatorName?.let { appendLine("操作人姓名: $it") }
                log.operatorEmployeeId?.let { appendLine("操作人工号: $it") }
                appendLine()
            }
            
            // 目标对象信息
            if (log.targetId != null || log.targetType != null || log.targetName != null) {
                appendLine("━━━━━━ 目标对象 ━━━━━━")
                log.targetId?.let { appendLine("目标ID: $it") }
                log.targetType?.let { appendLine("目标类型: $it") }
                log.targetName?.let { appendLine("目标名称: $it") }
                appendLine()
            }
            
            // 详细数据
            log.detailData?.let {
                appendLine("━━━━━━ 详细数据 ━━━━━━")
                appendLine(it)
                appendLine()
            }
            
            // 错误信息
            if (log.errorMessage != null || log.errorCode != null) {
                appendLine("━━━━━━ 错误信息 ━━━━━━")
                log.errorCode?.let { appendLine("错误代码: $it") }
                log.errorMessage?.let { appendLine("错误描述: $it") }
                appendLine()
            }
            
            // 其他信息
            if (log.ipAddress != null || log.deviceInfo != null) {
                appendLine("━━━━━━ 其他信息 ━━━━━━")
                log.ipAddress?.let { appendLine("IP地址: $it") }
                log.deviceInfo?.let { appendLine("设备信息: $it") }
            }
        }

        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("日志详情")
            .setMessage(message.trim())
            .setPositiveButton("确定", null)
            .setNeutralButton("复制", { _, _ ->
                // 复制到剪贴板
                val clipboard = requireContext().getSystemService(android.content.Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
                val clip = android.content.ClipData.newPlainText("日志详情", message.trim())
                clipboard.setPrimaryClip(clip)
                showToast("已复制到剪贴板")
            })
            .show()
    }

    /**
     * 显示清空日志确认对话框
     */
    private fun showClearLogsConfirmation() {
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("确认清空")
            .setMessage("确定要清空所有操作日志吗？此操作不可恢复！")
            .setPositiveButton("确定") { _, _ ->
                clearAllLogs()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 清空所有日志
     */
    private fun clearAllLogs() {
        progressBar.visibility = View.VISIBLE
        btnClearLogs.isEnabled = false

        lifecycleScope.launch {
            try {
                // 删除所有日志
                repository.deleteAll()
                
                // 清空适配器数据
                adapter.setLogs(emptyList())
                
                // 更新UI
                updateUI(emptyList())
                
                // 更新统计信息
                tvTotalCount.text = "总数: 0"
                tvFilteredCount.text = "筛选结果: 0"
                
                // 显示成功消息
                showToast("已成功清空所有日志")
                
            } catch (e: Exception) {
                showToast("清空失败: ${e.message}")
                android.util.Log.e("OperationLogFragment", "Failed to clear logs", e)
            } finally {
                progressBar.visibility = View.GONE
                btnClearLogs.isEnabled = true
            }
        }
    }

    private fun showToast(message: String) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
    }
}